<template>
  <div style="position: fixed;z-index:100">
    <div
      id="chart_popup"
      class="popover ng-scope top am-flip-x"
      style="width:480px;left:-240px;top:-460px"
      :style="visablestyle"
    >
      <div class="arrow"></div>
      <h3
        style="background-color: #57c52c;color: #fff; "
        class="popover-title ng-binding"
        ng-bind-html="title"
        ng-show="title"
      >{{popupDataTitle}}<button
          id="popup-closer"
          type="button"
          class="close"
          @click="popupClose"
        >×</button></h3>
      <div class="popover-content ng-binding">
        <div
          id="aqichart1"
          style="width:450px; height:400px"
        >
        </div>
      </div>
    </div>

    <div
      style="width:480px; position:fixed; right:10px;"
      :style="{height: contentHeight+'px' }"
    >
      <div class="panel panel-info b-t-4x">
        <div class="panel-heading b-b b-light">
          乌海市不同程度污染天数统计
        </div>
        <div class="panel-body">
          <div
            id="charts-r1"
            :style="{height:(chartsrHeight-20)+'px'}"
          ></div>
        </div>
      </div>
      <div
        class="panel no-border"
        style="margin-bottom:15px; margin-top:15px; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);"
      >

        <div class="panel-body">
          <div
            id="charts-r2"
            :style="{height:chartsrHeight+'px'}"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import './index.css';
import { mapActions, mapGetters } from 'vuex';
import * as mapOper from '../../scripts/mapOper.js';
import PopUp from './PopUp';
let config = require('../../config/config');
import commonOper from '../../scripts/commonOper';
var _ = require('lodash');

export default {
  name: 'R10102',
  computed: {
    ...mapGetters(['map', 'contentHeight'])
  },
  data() {
    return {
      visablestyle: { display: 'block', top: '-460px' },
      //传递到弹窗组件中的数据
      popupData: {},
      popupDataTitle: '',
      chartsrHeight: 400,
      //radio默认选中的值
      r2radioValue: 'rmonth',
      //当前选中的监测点id
      currentJCD: '',
      r1Charts: null,
      r2Charts: null,
      //服务器保存在本地的数据
      r1LocalData: null,
      r2LocalData: null
    };
  },
  mounted() {
    /**
     * 设置图表高度
     */
    this.chartsrHeight = this.contentHeight / 2 - 40;
    /**
     * 清除地图
     */
    if (this.map) {
      let map = mapOper.removeAllLayers(this.map);
      this.changeMap({ map: map });

      let imap = mapOper.removeInteractions(this.map);
      this.changeMap({ map: imap });
      let omap = mapOper.removeAllOverlay(this.map);
      this.changeMap({ map: omap });

      var container = document.getElementById('chart_popup');
      let markerSetting = {
        map: this.map,
        element: container
      };
      let markerMap = mapOper.addMarker(markerSetting);
      this.changeMap({ map: markerMap });
      //加载监测点wfs图层
      let params = {
        this: this,
        url:
          config.baseMapUrl +
          'wuhai-wfsmap?SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAME=aqipoint&OUTPUTFORMAT=json',
        successFunc: response => {
          let that = this;

          let jsonFeature = response.data;
          let style = mapOper.getGeoJsonStyle('qyjcd');
          let wfsParams = {
            map: this.map,
            jsonData: jsonFeature,
            style: style,
            styleFunc: function(feature) {
              style.getText().setText(feature.get('name'));
              return style;
            },
            selectFunc: function(e) {
              if (e.target.getFeatures().getLength() == 1) {
                that.visablestyle.display = 'block';
                let feature = e.target.getFeatures().item(0);
                that.popupDataTitle = feature.get('name');

                let aqiparams = {
                  this: that,
                  data: { jcdName: [feature.get('name')] },
                  url: config.webapiUrl + '/airQually/getCurrentDayHourData',
                  successFunc: function(request) {
                    let xData = [];
                    let seriesData = [];
                    _.forEach(request.data.data, function(item) {
                      xData.push(item.timestamp);
                      seriesData.push(item.aqi);
                    });

                    let popset = {
                      map: that.map,
                      coordinate: feature.getGeometry().flatCoordinates
                    };
                    let optionr1 = {
                      title: {
                        text: '实时 AQI 数据'
                      },
                      tooltip: {
                        trigger: 'axis'
                      },
                      xAxis: {
                        data: xData
                      },
                      yAxis: {
                        splitLine: {
                          show: false
                        }
                      },
                      toolbox: {
                        left: 'center',
                        feature: {
                          dataZoom: {
                            yAxisIndex: 'none'
                          },
                          restore: {},
                          saveAsImage: {}
                        }
                      },
                      dataZoom: [
                        {
                          startValue: xData[0]
                        },
                        {
                          type: 'inside'
                        }
                      ],
                      visualMap: {
                        top: 10,
                        right: 10,
                        pieces: [
                          {
                            gt: 0,
                            lte: 50,
                            color: '#096'
                          },
                          {
                            gt: 50,
                            lte: 100,
                            color: '#ffde33'
                          },
                          {
                            gt: 100,
                            lte: 150,
                            color: '#ff9933'
                          },
                          {
                            gt: 150,
                            lte: 200,
                            color: '#cc0033'
                          },
                          {
                            gt: 200,
                            lte: 300,
                            color: '#660099'
                          },
                          {
                            gt: 300,
                            color: '#7e0023'
                          }
                        ],
                        outOfRange: {
                          color: '#999'
                        }
                      },
                      series: {
                        name: '实时 AQI 数据',
                        type: 'line',
                        data: seriesData,
                        markLine: {
                          silent: true,
                          data: [
                            {
                              yAxis: 50
                            },
                            {
                              yAxis: 100
                            },
                            {
                              yAxis: 150
                            },
                            {
                              yAxis: 200
                            },
                            {
                              yAxis: 300
                            }
                          ]
                        }
                      }
                    };

                    let r1 = this.$echarts.init(
                      document.getElementById('aqichart1')
                    );
                    r1.setOption(optionr1, true);
                    mapOper.showPopUp(popset);
                    let zoomparams = {
                      map: that.map,
                      center: [
                        feature.getGeometry().flatCoordinates[0] + 1500,
                        feature.getGeometry().flatCoordinates[1] + 1000
                      ],
                      zoom: 8
                    };
                    mapOper.ZoomAndCenter(zoomparams);
                  }
                };

                commonOper.HttpPost(aqiparams);
              } else {
                that.visablestyle.display = 'none';
              }
            }
          };
          let wfsmap = mapOper.loadWFSLayer(wfsParams);
          this.changeMap({ map: wfsmap });

          let overlayParams = {
            map: this.map,
            jsonData: response.data
          };
          let overlaymap = mapOper.loadOverlay(overlayParams);
          this.changeMap({ map: overlaymap });
        },
        failFunc: response => {
          console.log(response);
        }
      };
      commonOper.HttpGet(params);

      
    } else {
      this.$router.push({
        //核心语句
        path: 'R101.html' //跳转的路径
      });
    }
  },
  created() {
    this.lazyLoad('');
  },
  methods: {
    popupClose() {
      this.visablestyle.display = 'none';
    },
    //更新右侧图表
    updateAllCharts() {
      let r1 = this.$echarts.init(document.getElementById('charts-r1'));
      let r2 = this.$echarts.init(document.getElementById('charts-r2'));
      r1.showLoading(); 
      r2.showLoading(); 
      let r1option = {
        color:['#096','#ffde33','#ff9933','#cc0033','#660099','#7e0023','#034abc','#0910ef','#078cde','#056bcd','#888abc', '#345678'],
        legend: {
          type: 'scroll',
          // data: ['优', '良', '轻度污染', '中度污染', '重度污染', '严重污染', '2015', '2016', '2017', '2018', '2019']
        },
        tooltip: {},
        dataset: {
          source: [
            ['年度', '2015', '2016', '2017', '2018','2019']
            
          ]
        },
        xAxis: [
          {type: 'category', gridIndex: 0},
          {type: 'category', gridIndex: 1}
        ],
        yAxis: [
          {gridIndex: 0},
          {gridIndex: 1}
        ],
        grid: [
          {bottom: '55%'},
          {top: '55%'}
        ],
        series: [
        // These series are in the first grid.
          {type: 'bar', seriesLayoutBy: 'row'},
          {type: 'bar', seriesLayoutBy: 'row'},
          {type: 'bar', seriesLayoutBy: 'row'},
          {type: 'bar', seriesLayoutBy: 'row'},
          {type: 'bar', seriesLayoutBy: 'row'},
          {type: 'bar', seriesLayoutBy: 'row'},
          {type: 'bar', seriesLayoutBy: 'row'},
          // These series are in the second grid.
          {type: 'bar', xAxisIndex: 1, yAxisIndex: 1},
          {type: 'bar', xAxisIndex: 1, yAxisIndex: 1},
          {type: 'bar', xAxisIndex: 1, yAxisIndex: 1},
          {type: 'bar', xAxisIndex: 1, yAxisIndex: 1},
          {type: 'bar', xAxisIndex: 1, yAxisIndex: 1}
        ]
      };

      let r2option = {
        title: {
          text: '乌海市历年 AQI 指数'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          data: []
        },
        yAxis: {
          splitLine: {
            show: false
          }
        },
       
        dataZoom: [{
          startValue: ''
        }, {
          type: 'inside'
        }],
        visualMap: {
          top: 10,
          right: 10,
          pieces: [{
            gt: 0,
            lte: 50,
            color: '#096'
          }, {
            gt: 50,
            lte: 100,
            color: '#ffde33'
          }, {
            gt: 100,
            lte: 150,
            color: '#ff9933'
          }, {
            gt: 150,
            lte: 200,
            color: '#cc0033'
          }, {
            gt: 200,
            lte: 300,
            color: '#660099'
          }, {
            gt: 300,
            color: '#7e0023'
          }],
          outOfRange: {
            color: '#999'
          }
        },
        series: {
          name: '乌海市历年 AQI 指数',
          type: 'line',
          data: [],
          markLine: {
            silent: true,
            data: [{
              yAxis: 50
            }, {
              yAxis: 100
            }, {
              yAxis: 150
            }, {
              yAxis: 200
            }, {
              yAxis: 300
            }]
          }
        }
      };
      let params = {
        this: this,
        url: config.webapiUrl + '/airQually/getHistoryDayData?cityName=乌海市',
        successFunc: function(request) {
          r1.hideLoading(); 
          r2.hideLoading(); 
          let sortedarr=_.sortBy(request.data.data, ['timestamp']);
         
          let yearList=[];
          let xData = [];
          let seriesData = [];

          _.forEach(sortedarr, function(item) {
            xData.push(item.timestamp);
            seriesData.push(item.aqi);
            let numAqi=Number(item.aqi);
            let curLv='lv1';
            if( numAqi<50){
              curLv='lv1';
            }else if(numAqi<100&&numAqi>=50){
              curLv='lv2';
            }else if(numAqi<150&&numAqi>=100){
              curLv='lv3';
            }else if(numAqi<200&&numAqi>=150){
              curLv='lv4';
            }else if(numAqi<300&&numAqi>=200){
              curLv='lv5';
            }else if(numAqi>=300){
              curLv='lv6';
            }else{
              curLv='lv1';
            }
            yearList.push({year:item.timestamp.split('-')[0],aqilv:curLv});
          });
         
          let grouplv=_.groupBy(yearList, function(item){return item.aqilv;});
          let lv1count=_.countBy(grouplv.lv1, function(o){return o.year;});
          let lv2count=_.countBy(grouplv.lv2, function(o){return o.year;});
          let lv3count=_.countBy(grouplv.lv3, function(o){return o.year;});
          let lv4count=_.countBy(grouplv.lv4, function(o){return o.year;});
          let lv5count=_.countBy(grouplv.lv5, function(o){return o.year;});
          let lv6count=_.countBy(grouplv.lv6, function(o){return o.year;});

          //lv1
          let lv1Obj=['优',lv1count['2015']===undefined?0:lv1count['2015'],lv1count['2016']===undefined?0:lv1count['2016'],lv1count['2017']===undefined?0:lv1count['2017'],lv1count['2018']===undefined?0:lv1count['2018'],lv1count['2019']===undefined?0:lv1count['2019']];
          let lv2Obj=['良',lv2count['2015']===undefined?0:lv2count['2015'],lv2count['2016']===undefined?0:lv2count['2016'],lv2count['2017']===undefined?0:lv2count['2017'],lv2count['2018']===undefined?0:lv2count['2018'],lv2count['2019']===undefined?0:lv2count['2019']];
          let lv3Obj=['轻度污染',lv3count['2015']===undefined?0:lv3count['2015'],lv3count['2016']===undefined?0:lv3count['2016'],lv3count['2017']===undefined?0:lv3count['2017'],lv3count['2018']===undefined?0:lv3count['2018'],lv3count['2019']===undefined?0:lv3count['2019']];
          let lv4Obj=['中度污染',lv4count['2015']===undefined?0:lv4count['2015'],lv4count['2016']===undefined?0:lv4count['2016'],lv4count['2017']===undefined?0:lv4count['2017'],lv4count['2018']===undefined?0:lv4count['2018'],lv4count['2019']===undefined?0:lv4count['2019']];
          let lv5Obj=['重度污染',lv5count['2015']===undefined?0:lv5count['2015'],lv5count['2016']===undefined?0:lv5count['2016'],lv5count['2017']===undefined?0:lv5count['2017'],lv5count['2018']===undefined?0:lv5count['2018'],lv5count['2019']===undefined?0:lv5count['2019']];
          let lv6Obj=['严重污染',lv6count['2015']===undefined?0:lv6count['2015'],lv6count['2016']===undefined?0:lv6count['2016'],lv6count['2017']===undefined?0:lv6count['2017'],lv6count['2018']===undefined?0:lv6count['2018'],lv6count['2019']===undefined?0:lv6count['2019']];
          
          // console.log(lv1Obj);
          r1option.dataset.source.push(lv1Obj);
          r1option.dataset.source.push(lv2Obj);
          r1option.dataset.source.push(lv3Obj);
          r1option.dataset.source.push(lv4Obj);
          r1option.dataset.source.push(lv5Obj);
          r1option.dataset.source.push(lv6Obj);
          console.log(r1option.dataset.source);

          r2option.xAxis.data=xData;
          r2option.dataZoom[0].startValue=xData[0];
          r2option.series.data=seriesData;
          r2.setOption(r2option, true);
          window.onresize = r2.resize;

          
          r1.setOption(r1option, true);
          
          window.onresize = r1.resize;
        }
      };
      commonOper.HttpGet(params);
      
    },
    
    lazyLoad() {
      setTimeout(() => {
        this.updateAllCharts();
      }, 500);
    },

    ...mapActions(['changeMap'])
  },
  components: {
    PopUp
  }
};
</script>


